#!/usr/bin/env python3
"""
Example of using react_terminal with the independent monitoring server
This shows how to integrate monitoring without modifying the core react_agent code
"""

import asyncio
import sys
import os

# Add parent directory to path
try:
    parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sys.path.append(parent_dir)
    from base_code import *
    from base_code.common import *
except ImportError:
    print("Error: Cannot find 'base_code' module. Please ensure pocketflow code is in correct path.")
    sys.exit(1)

# Import react components
try:
    from react_agent import ReActAgent
    from local_tools import GLOBAL_TOOL_SYSTEM
    from monitor_integration import setup_monitoring_for_terminal
except ImportError as e:
    print(f"Error importing modules: {e}")
    sys.exit(1)

class ReactTerminalWithMonitoring:
    """React terminal with independent monitoring support"""

    def __init__(self):
        self.agent = None
        self.monitor_integration = None

    async def start(self, monitor_port: int = 8000):
        """Start the terminal with monitoring"""
        print("Starting React Terminal with Independent Monitoring...")
        print("=" * 60)

        # Step 1: Setup monitoring (independent server)
        print(f"Step 1: Starting monitoring server on port {monitor_port}...")
        self.monitor_integration = setup_monitoring_for_terminal(port=monitor_port)
        print(f"Monitoring server started!")
        print(f"Web interface available at: http://localhost:{monitor_port}")
        print()

        # Wait for server to start
        await asyncio.sleep(2)

        # Step 2: Create agent (no modifications needed)
        print("Step 2: Creating ReActAgent...")
        self.agent = ReActAgent(
            tools_system=GLOBAL_TOOL_SYSTEM,
            local_llm="qwen3:4b",
            remote_llm="qwen3-plus"
        )
        print("ReActAgent created successfully")
        print()

        # Step 3: Connect agent to monitor
        print("Step 3: Connecting agent to monitor...")
        self.monitor_integration.connect_agent(self.agent)
        print("Agent connected to monitor!")
        print()

        print("=" * 60)
        print("React Terminal is ready!")
        print("Commands you can try:")
        print("  - 'What is 2 + 2?'")
        print("  - 'List files in current directory'")
        print("  - 'Read a PDF file'")
        print("  - 'What is the weather like?'")
        print()
        print("Monitor the agent's memory at: http://localhost:8000")
        print("Type 'quit' to exit, 'status' to see monitor status")
        print("=" * 60)
        print()

        # Start interactive terminal
        await self.interactive_terminal()

    async def interactive_terminal(self):
        """Interactive terminal loop"""
        while True:
            try:
                # Get user input
                user_input = input("react_agent> ").strip()

                if not user_input:
                    continue

                # Handle special commands
                if user_input.lower() == 'quit':
                    print("Exiting React Terminal...")
                    break

                elif user_input.lower() == 'status':
                    status = self.monitor_integration.get_status()
                    print(f"Monitor Status:")
                    print(f"  Server Running: {status['server_running']}")
                    print(f"  Agent Connected: {status['agent_connected']}")
                    print(f"  Port: {status['port']}")
                    print(f"  Timeline Events: {status['timeline_length']}")
                    continue

                # Record start of task
                self.monitor_integration.record_event("user_input_received")

                # Process the command
                print(f"Processing: {user_input}")
                result = await self.agent.process_command_async(user_input)

                # Display result
                print(f"Result: {result}")

                # Record completion
                self.monitor_integration.record_event("task_completed")

                # Show memory info if available
                if hasattr(self.agent, 'show_memo'):
                    self.agent.show_memo(verbose=False)

            except KeyboardInterrupt:
                print("\nUse 'quit' to exit properly")
                continue

            except Exception as e:
                print(f"Error processing command: {e}")
                self.monitor_integration.record_event("error_occurred")

    async def shutdown(self):
        """Shutdown the terminal"""
        if self.monitor_integration:
            self.monitor_integration.disconnect_agent()
            print("Agent disconnected from monitor")

        print("React Terminal shutdown complete")

async def main():
    """Main entry point"""
    terminal = ReactTerminalWithMonitoring()

    try:
        await terminal.start(monitor_port=8000)
    except KeyboardInterrupt:
        print("\nShutting down React Terminal...")
    finally:
        await terminal.shutdown()

if __name__ == "__main__":
    print("React Terminal with Independent Monitoring")
    print("This demonstrates loose coupling between agent and monitoring")
    print()

    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nProgram interrupted by user")
    except Exception as e:
        print(f"Program error: {e}")
        import traceback
        traceback.print_exc()